﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Resources;

using System.Data;
using DDSC.OracleADO;
using System.Collections;
using System.Text;

/// <summary>
///  模組: ASP.NET網頁共用基底類別
///  作者: Adams <adams@netdb.com.tw>
///  修改: 2013-3-30
///  目的: 此基底類別為整個專案共用，想要控管權限的網頁要繼承此類別
/// </summary>
public class BasePermissionPage : System.Web.UI.Page
{
    //Modify By Ben 20130621 修改傳遞方式=======
    //紀錄Grid裡面的Key用於傳遞到維護頁
    public Dictionary<string, string> g_GridKey { get; set; }
    //紀錄查詢條件
    public Dictionary<string, string> g_ConditionKey { get; set; }

    /// <summary>
    /// 定維護Key值
    /// </summary>
    /// <param name="p_Param"></param>
    /// <param name="p_ConditionKey"></param>
    /// <returns></returns>
    [System.Web.Services.WebMethod]
    public static void SetGridKey(Dictionary<string, string> p_Param, Dictionary<string, string> p_ConditionKey)
    {
        ArrayList m_ArrayList = new ArrayList();
        m_ArrayList.Add(p_ConditionKey);
        m_ArrayList.Add(p_Param);
        HttpContext.Current.Session.Add(GetSessionName(), m_ArrayList);

    }
    public static String GetSessionName()
    {
        String m_Name = HttpContext.Current.Request.Url.AbsolutePath.ToString();
        return m_Name.Substring(0, m_Name.ToUpper().IndexOf(".ASPX")).Split('/').Last();
    }

    public static String GetKeySessionName()
    {
        String m_Name = "";
        if (HttpContext.Current.Request.UrlReferrer != null)
        {
            m_Name = HttpContext.Current.Request.UrlReferrer.ToString();
            m_Name = m_Name.Substring(0, m_Name.ToUpper().IndexOf(".ASPX")).Split('/').Last();

        }
        return m_Name;
    }

    public ArrayList SetKey(string p_Name)
    {
        ArrayList m_ArrayList = new ArrayList();
        //紀錄Grid裡面的Key用於傳遞到維護頁
        if (Session[p_Name] != null)
        {
            m_ArrayList = (ArrayList)Session[p_Name];
            g_GridKey = (Dictionary<string, string>)m_ArrayList[1];
            g_ConditionKey = (Dictionary<string, string>)m_ArrayList[0];
        }
        return m_ArrayList;
    }
    //Modify By Ben 20130621 修改傳遞方式=======
    //Grid公用屬性 Add By Ben 20130429
    public class PageInfo
    {
        public string OrderBy { get; set; }
        public int? PageIndex { get; set; }
        public int? PageSize { get; set; }
        public string TargetDiv { get; set; }
    }
    /// <summary>
    /// Grid 分頁,計算筆數,轉成JSON格式 Add By Ben 20130429
    /// </summary>
    /// <param name="p_sb">SQL語法</param>
    /// <param name="p_arrParam">條件參數</param>
    /// <param name="p_PageInfo">頁面資訊物件</param>
    /// <returns></returns>
    public static Boolean his_flag = false; //用來判斷是不是歷史資料
    public static object ADOGridHandler(StringBuilder p_sb, ArrayList p_arrParam, PageInfo p_PageInfo)
    {
        int pageSize = p_PageInfo.PageSize.HasValue ? p_PageInfo.PageSize.Value : 10; //每頁幾筆 
        int pageNum = p_PageInfo.PageIndex.HasValue ? p_PageInfo.PageIndex.Value : 1;  //第幾頁
        int m_Position = (Convert.ToInt32(pageNum) - 1) * Convert.ToInt32(pageSize);//起始比數
        //判斷是不是要抓歷史檔
        if (p_sb.ToString().IndexOf("--History") >= 0)
        {
            his_flag = true;
            p_sb.Replace("--History","");
        }

        if (p_PageInfo.OrderBy != "")//排序條件 
            p_sb.Append(" Order By " + p_PageInfo.OrderBy);

        dbAccess m_dba = new dbAccess();
        StringBuilder m_sbCount = new StringBuilder();
        Object results = new Object();

        DataSet ds = m_dba.runExecuteQuery("Table", p_sb.ToString(), m_Position, pageSize, p_arrParam);
        if ((ds.Tables["info"].Rows[0]["ReturnCode"].ToString() != "100" && ds.Tables["info"].Rows[0]["ReturnCode"].ToString() != "999"))
        {
            ArrayList m_arrParam = p_arrParam;
            System.Data.DataSet ds_Count = new System.Data.DataSet();
            m_sbCount.Append("select count(*) RowCount from ( " + p_sb.ToString() + " ) ");
            ds_Count = m_dba.runExecuteQuery("Table", m_sbCount.ToString(), m_arrParam);
            var totalRecords = Convert.ToInt32(ds_Count.Tables["Table"].Rows[0]["RowCount"].ToString());
            int totalPages = (int)Math.Ceiling((float)totalRecords / (float)pageSize); //總共幾頁

            results = m_dba.RowsToDictionary(ds.Tables["Table"], totalRecords.ToString(), totalPages.ToString());
        }
        else
        {
            //需再讀AS400_ZDF631Z歷史檔 by vicky
            if (his_flag && (ds.Tables["info"].Rows[0]["ReturnCode"].ToString() == "100"))
            {
                p_sb.Replace("AS400_ZDF631", "AS400_ZDF631Z");

                ds = m_dba.runExecuteQuery("Table", p_sb.ToString(), m_Position, pageSize, p_arrParam);
                if ((ds.Tables["info"].Rows[0]["ReturnCode"].ToString() != "100" && ds.Tables["info"].Rows[0]["ReturnCode"].ToString() != "999"))
                {
                    ArrayList m_arrParam = p_arrParam;
                    System.Data.DataSet ds_Count = new System.Data.DataSet();
                    m_sbCount.Append("select count(*) RowCount from ( " + p_sb.ToString() + " ) ");
                    ds_Count = m_dba.runExecuteQuery("Table", m_sbCount.ToString(), m_arrParam);
                    var totalRecords = Convert.ToInt32(ds_Count.Tables["Table"].Rows[0]["RowCount"].ToString());
                    int totalPages = (int)Math.Ceiling((float)totalRecords / (float)pageSize); //總共幾頁

                    results = m_dba.RowsToDictionary(ds.Tables["Table"], totalRecords.ToString(), totalPages.ToString());
                }
                else
                {
                    results = m_dba.RowsToDictionary(ds.Tables["info"], "0", "0");
                }
            }
            else
            {
                results = m_dba.RowsToDictionary(ds.Tables["info"], "0", "0");
            }
        }
        return (results);

    }

  /// <summary>
  ///控管每一個頁面中控制項的權限，改寫PreRender事件
  ///可搭配網頁中GridView或ListView的DataBind()方法
  /// </summary>   
  protected void Page_PreRender(object sender, EventArgs e)
  {
    try
    {
      var allControls = ControlUtil.FindControlsOfType<WebControl>(Page);
      //foreach (var item in allControls)
      //{
      //  Response.Write(item.ID + "<br/>");
      //}
      using (MISEntities mis = new MISEntities())
      {
        //找出目前網頁在授權功能中之控制項ID(有找到代表要顯示)
        var function = mis.MIS_FUNCTION_AP
            .Where(f => f.FUNCTION_PATH.ToLower().Contains(Request.AppRelativeCurrentExecutionFilePath.ToLower()))
            .SingleOrDefault();
        if (function != null)
        {
          var count = mis.MIS_AUTHORIZOR_AP.Where(a => a.FUNCTION_ID == function.FUNCTION_ID && a.USER_ID == User.Identity.Name).Count();
          if (function.IS_DEFULT_AUTH == "N" || (function.IS_DEFULT_AUTH == "Y" && count > 0))
          {
            var auth_controls = mis.MIS_AUTHORIZOR_AP
             .Where(a => a.FUNCTION_ID == function.FUNCTION_ID && a.USER_ID == User.Identity.Name)
             .Select(a => a.CONTROL_ID).Distinct().ToArray();

            var controls = mis.MIS_CONTROL_AP.Select(c => c.CONTROL_ID.ToLower()).ToArray();
            var matchControls = allControls.Where(c => controls.Contains(c.ID));
            matchControls.Where(m => !auth_controls.Contains(m.ID.ToLower())).ToList().ForEach(c => c.Visible = false);
            //matchControls.Where(m => auth_controls.Contains(m.ID)).ToList().ForEach(c => c.Visible=true);
          }
        }
      }

      try
      {
        //載入每一頁最後查詢條件資料
      string pageUrl = Request.AppRelativeCurrentExecutionFilePath;
      if (((ProfileCommon)HttpContext.Current.Profile).PageConditionRecord != null)
      {
        List<ControlItem> ControlItems;
        if (((ProfileCommon)HttpContext.Current.Profile).PageConditionRecord.PageItem.TryGetValue(pageUrl, out ControlItems))
        {
          //var allControls = ControlUtil.FindControlsOfType<WebControl>(Page);
          var ConditionControls = ControlItems.Select(c => c.ControlID.ToLower()).ToArray();
          var ConditionMatchControls = allControls.Where(c => ConditionControls.Contains(c.ID.ToLower()));
          foreach (var matchControl in ConditionMatchControls)
          {
            if (matchControl != null)
            {
              var record = ControlItems.Where(c => c.ControlID.ToLower() == matchControl.ID.ToLower()).SingleOrDefault();
              if (record != null)
              {
                if (matchControl is TextBox)
                {
                  (matchControl as TextBox).Text = record.ControlValue;
                }
                if (matchControl is DropDownList)
                {
                  (matchControl as DropDownList).SelectedValue = record.ControlValue;
                }
              }
            }
          }
        }
      }      
      }
      catch (Exception)
      {
        //ConditionMatchControls跑到最後為NULL物件，因此不處理!(無誤)
      }

      var resources = LanguageUtil.GetItemsFromResource(MessageResource.ResourceManager);
      var matchResources = allControls.Where(c => resources.Select(r => r.Key).Contains(c.ID));
      foreach (WebControl control in matchResources)
      {
        if (control is Button)
        {
          Button btn = control as Button;
          var matchValue = resources.Where(r => r.Key == btn.ID).Select(r => r.Value).SingleOrDefault();
          if (matchValue != null)
          {
            btn.Text = matchValue;
          }
        }
      }

      //將資料權限

    }
    catch (Exception ex)
    {
      throw ex;
    }
  }

  protected override void InitializeCulture()
  {   
    base.InitializeCulture();
  }

  public override void VerifyRenderingInServerForm(Control control)
  {
    
  }
  //將頁面錯誤寫入資料庫
  public string ERROR_DBSAVE(string PROG_NAME, string FUNC_NAME, string error_msg, string USER, string ERR_STATUS, string ERR_CODE, string ERR_DATA)
  {
      try
      {
          ddscDataSet m_ddscDs = new ddscDataSet();
          dbAccess m_dba = new dbAccess();
          ddscDataTable p_ddscDataTable = m_ddscDs.createDataTable("DS_DEF_REC");
          DataBase dataBase = new DataBase();
          // 宣告回傳DataSet
          DataSet dsResult = new DataSet();

          p_ddscDataTable.addNewRow();
          p_ddscDataTable.setColumnValue("action", "VARCHAR", "ADD");
          p_ddscDataTable.setColumnValue("ERR_DATE", "VARCHAR", System.DateTime.Now.ToString("yyyyMMdd"));
          p_ddscDataTable.setColumnValue("err_procedure", "VARCHAR", PROG_NAME.Length > 40 ? PROG_NAME.Substring(PROG_NAME.Length - 40) : PROG_NAME); //從右取40位
          
          p_ddscDataTable.setColumnValue("ERR_STATS", "VARCHAR", ERR_STATUS);
          p_ddscDataTable.setColumnValue("ERR_CODE", "NUMBER", 0);
          p_ddscDataTable.setColumnValue("ERR_DATA", "NCLOB", ERR_DATA);
          p_ddscDataTable.setColumnValue("ERR_TEXT", "VARCHAR", error_msg);

          p_ddscDataTable.setColumnValue("create_time", "VARCHAR", System.DateTime.Now.ToString("HHmmss"));

          if (p_ddscDataTable.Rows.Count > 1)
          {
              m_ddscDs.addddscDataTable(p_ddscDataTable);
          }
          // 執行編輯method
          DataBase m_DataBase = new DataBase();
          dsResult = m_DataBase.AdditionParameter(m_ddscDs);
          string strResult = dsResult.Tables[0].Rows[0]["TransResult"].ToString();
          string strMessage = dsResult.Tables[0].Rows[0]["Message"].ToString();
          string strLogMessage = dsResult.Tables[0].Rows[0]["LogMessage"].ToString();
          if (strResult == "T")
          {
              return "成功!";

          }
          else
          {
              return "error" + strMessage;
          }

      }
      catch (Exception ex)
      {
          return ex.Message;
      }

  }
  public string BP_Message = "程式發生錯誤!";

  //判斷頁面上Control的權限
  //public DataSet Auth_Controls()
  //{
  //    string page_path = Request.AppRelativeCurrentExecutionFilePath.ToLower();

  //    DataSet ds = null;
  //    try
  //    {
  //        dbAccess m_dba = new dbAccess();
  //        StringBuilder m_sb = new StringBuilder();
  //        ArrayList m_arrParam = new ArrayList();

  //        m_sb.Append(" select X.CONTROL_ID,Y.CONTROL_ID AUTH_CONTROL ");
  //        m_sb.Append(" from MIS_CONTROL_AP X  ");
  //        m_sb.Append(" left join (select USER_ID,FUNCTION_ID,CONTROL_ID from MIS_AUTHORIZOR_AP A where A.USER_ID = :USER_ID) Y on X.CONTROL_ID = Y.CONTROL_ID ");
  //        m_sb.Append(" inner join (select FUNCTION_ID,FUNCTION_PATH from MIS_FUNCTION_AP A WHERE A.FUNCTION_TYPE = 'FUNCTION' and LOWER(FUNCTION_PATH) =:page_path) Z  on Y.FUNCTION_ID = Z.FUNCTION_ID ");
  //        m_arrParam.Add(m_dba.GetOracleParam(":USER_ID", User.Identity.ToString()));
  //        m_arrParam.Add(m_dba.GetOracleParam(":page_path", page_path.ToLower()));
  //        ds = m_dba.runExecuteQuery("DEPT", m_sb.ToString(), m_arrParam);
          

  //    }
  //    catch (Exception ex)
  //    {
          
  //        ERROR_DBSAVE(Page.ToString(), "DBINT", ex.Message, "", "c#", "0", ex.StackTrace);
  //        throw ex;
  //    }
  //    return ds;
  //}
}